// 获取应用ID
const urlParams = new URLSearchParams(window.location.search);
const appId = urlParams.get('id');

// 组件定义
const components = {
    button: {
        template: `
            <div class="component-wrapper">
                <button class="component-button">{{ text }}</button>
            </div>
        `,
        props: {
            text: {
                type: String,
                default: '按钮'
            }
        }
    },
    input: {
        template: `
            <div class="component-wrapper">
                <input type="text" class="component-input" :placeholder="placeholder">
            </div>
        `,
        props: {
            placeholder: {
                type: String,
                default: '请输入'
            }
        }
    },
    label: {
        template: `
            <div class="component-wrapper">
                <label class="component-label">{{ text }}</label>
            </div>
        `,
        props: {
            text: {
                type: String,
                default: '标签'
            }
        }
    },
    container: {
        template: `
            <div class="component-wrapper container">
                <slot></slot>
            </div>
        `
    }
};

// Vue实例
new Vue({
    el: '#app',
    data: {
        currentTab: 'visual',
        currentFile: 'template',
        layout: [],
        components: [
            { type: 'button', label: '按钮' },
            { type: 'input', label: '输入框' },
            { type: 'label', label: '标签' },
            { type: 'container', label: '容器' }
        ],
        editor: null,
        appContent: {
            template: '',
            script: '',
            style: ''
        }
    },
    async created() {
        // 加载应用内容
        await this.loadAppContent();
        // 初始化Monaco编辑器
        this.initMonacoEditor();
    },
    methods: {
        // 加载应用内容
        async loadAppContent() {
            try {
                const response = await fetch(`/api/apps/${appId}/content`);
                const data = await response.json();
                if (data.success) {
                    this.appContent = data.content;
                    // 初始化布局
                    this.initLayout(data.content.template);
                } else {
                    showStatus(data.error, 'error');
                }
            } catch (error) {
                showStatus('加载应用内容失败', 'error');
            }
        },
        
        // 初始化Monaco编辑器
        initMonacoEditor() {
            require(['vs/editor/editor.main'], () => {
                this.editor = monaco.editor.create(document.getElementById('monaco-editor'), {
                    value: this.appContent.template,
                    language: 'html',
                    theme: 'vs-dark',
                    automaticLayout: true
                });
                
                // 监听文件切换
                this.$watch('currentFile', (file) => {
                    this.editor.setValue(this.appContent[file]);
                    this.editor.updateOptions({
                        language: file === 'template' ? 'html' : 
                                 file === 'script' ? 'javascript' : 'css'
                    });
                });
            });
        },
        
        // 初始化布局
        initLayout(template) {
            // 这里需要解析模板，转换为布局数据
            // 暂时使用空布局
            this.layout = [];
        },
        
        // 拖拽开始
        onDragStart(event, component) {
            event.dataTransfer.setData('component', JSON.stringify(component));
        },
        
        // 布局更新
        onLayoutUpdated(newLayout) {
            this.layout = newLayout;
            this.updateTemplate();
        },
        
        // 更新模板
        updateTemplate() {
            // 将布局转换为HTML模板
            let template = '';
            this.layout.forEach(item => {
                const component = components[item.component];
                if (component) {
                    template += this.generateComponentHTML(item, component);
                }
            });
            this.appContent.template = template;
            this.editor.setValue(template);
        },
        
        // 生成组件HTML
        generateComponentHTML(item, component) {
            const props = item.props || {};
            let html = component.template;
            
            // 替换属性
            Object.entries(props).forEach(([key, value]) => {
                html = html.replace(`{{ ${key} }}`, value);
            });
            
            return html;
        },
        
        // 保存内容
        async saveContent() {
            try {
                // 更新内容
                this.appContent[this.currentFile] = this.editor.getValue();
                
                const response = await fetch(`/api/apps/${appId}/content`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(this.appContent)
                });
                
                const data = await response.json();
                if (data.success) {
                    showStatus('保存成功', 'success');
                } else {
                    showStatus(data.error, 'error');
                }
            } catch (error) {
                showStatus('保存失败', 'error');
            }
        },
        
        // 预览
        preview() {
            const previewContent = document.createElement('div');
            previewContent.innerHTML = this.appContent.template;
            
            // 添加样式
            const styleSheet = document.createElement('style');
            styleSheet.textContent = this.appContent.style;
            previewContent.appendChild(styleSheet);
            
            // 添加脚本
            const script = document.createElement('script');
            script.textContent = this.appContent.script;
            previewContent.appendChild(script);
            
            this.$refs.previewContainer.innerHTML = '';
            this.$refs.previewContainer.appendChild(previewContent);
        }
    }
});

// 显示状态消息
function showStatus(message, type = 'info') {
    const statusMessage = document.createElement('div');
    statusMessage.className = `status-message ${type}`;
    statusMessage.textContent = message;
    document.body.appendChild(statusMessage);
    
    setTimeout(() => {
        statusMessage.remove();
    }, 3000);
} 